const user = require('./DB/userDB.js');
const userPrize = require('./DB/userPrizeDB.js');
const prize = require('./DB/prizeDB.js');
const dateFormat = require('dateformat');

exports.main = async (context) => {
    const {cloud } = context;
   
    console.log("cloud.dataspace.executeSql",cloud.dataspace.executeSql);
     return 'hello world';
};

//创建或查询
exports.getUserInfo = async (context) => {
    const {cloud, mixNick, data} = context;
    const info = {
        chance: 1,
        user_id: 0
    };

    try{
        let select_info = await user.findUserByMixNick(cloud, mixNick);
        console.log('select_info--------------', select_info.data.length);

        if(select_info.status == "success"){
            if(select_info.data.length){
                info.chance = select_info.data[0].chance;
                info.user_id = select_info.data[0].id;
            }else{
                let create_info = await user.createUser(cloud, mixNick, data);
                console.log('create_info-----------', create_info);

                if(create_info.data.affectedRows){
                    info.chance = 1;
                    info.user_id = create_info.data.insertId;
                }
            }

            return {
                status: "success",
                data: info
            }
        }else{
            return {
                status: "fail",
                data: info
            }   
        }
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
};

//查询所有中奖信息
exports.getAllPrizeUserInfo = async (context) => {
    const { cloud, mixNick, data } = context;
    const info = {
        allPrizeDate: [],
        allPrizeInfo: [],
        selfPrizeInfo: []
    }

    try{
        let select_all_info = await userPrize.findAllUerInfo(cloud);
        let allPrizeInfo = select_all_info.info;

        for(let i = 0; i < allPrizeInfo.length; i++){
            let date = allPrizeInfo[i].win_date;
            let hasDate = false;

            for(let j = 0; j < info.allPrizeDate.length; j++){
                if(date == info.allPrizeDate[j]){
                    hasDate = true;
                    info.allPrizeInfo[j].push(allPrizeInfo[i]);
                    break;
                }
            }

            if(hasDate){
                continue;
            }
            
            info.allPrizeDate.push(date);
            
            let arr = [];
            arr.push(allPrizeInfo[i]);
            info.allPrizeInfo.push(arr);
        }


        let select_self_info = await userPrize.findPrizeUserInfo(cloud, mixNick, data);
        info.selfPrizeInfo = select_self_info.info;

        return {
            status: "success",
            data: info
        }
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
};

//查询用户中奖信息
exports.getUserPrizeInfo = async (context) => {
    const { cloud, mixNick, data } = context;

    try{
        let select_info = await userPrize.findPrizeUserCount(cloud, mixNick, data);

        return {
            status: "success",
            data: select_info.info[0]
        }
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
};

//查询用户抽奖机会
exports.getUserChance = async (context) => {
    const {cloud, mixNick, data} = context;
    const info = {
        chance: 0
    };

    try{
        let select_info = await user.findUserByUserId(cloud, data);
        console.log('select_info--------------', select_info.data.length);

        if(select_info.status == "success"){
            if(select_info.data.length){
                info.chance = select_info.data[0].chance;
            }

            return {
                status: "success",
                data: info
            }
        }else{
             return {
                status: "success",
                data: info
            }   
        }
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
}

//更新用户中奖信息
exports.updateUserPrizeInfo = async (context) => {
    const {cloud, data, mixNick} = context;

    try{
        if(data.user_id){
            let select_user_info = await user.findUserByIdAndMixnick(cloud, data, mixNick);

            if(select_user_info.data.length){
                let update_user_prize_info = await userPrize.updatePrizeInfo(cloud, data, mixNick);
                console.log('update_user_prize_info---------', update_user_prize_info);

                if(update_user_prize_info.info.affectedRows){
                    return {
                        status: "success",
                        data: true
                    }
                }else{
                    return {
                        status: "fail",
                        data: "更新信息失败"
                    }
                }
            }else{
                return {
                    status: "fail",
                    data: "该用户不存在"
                }
            }
        }else{
            return {
                status: "fail",
                data: "该用户不存在"
            }
        }
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
}

//每日凌晨更新chance数据
exports.updateChance = async (context) => {
    const {cloud} = context;
    try{
        let update_info = await user.addUserChance(cloud);

        return {
            status: "success",
            data: true
        }
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
};

//抽奖
exports.luckDraws = async (context) => {
    const { cloud, mixNick, data: {user_id, nick, type} } = context;
    const info = {
        award_type: 0,
        chance: 1,
        goods_url: ""
    }

    //添加事物
    const connection = await cloud.dataspace.beginTransaction();
    try {
        // 查询抽奖机会
        let select_chance_sql = 'select chance from el_user where id = ?';
        const luckDrawNum = await connection.executeSql(select_chance_sql, [user_id]);
        console.log("===============luckDrawNum.length================", luckDrawNum[0].chance);

        if (luckDrawNum[0].chance) {
            // 消耗机会
            let update_chance_sql = 'update el_user set chance = 0 where id = ? and chance > 0';
            let updateUserDrawNum = await connection.executeSql(update_chance_sql, [user_id]);
            console.log("=============updateUserDrawNum==============", updateUserDrawNum);

            if (updateUserDrawNum.affectedRows) {
                //查询中奖纪录
                let select_user_prize_sql = 'select count(*) as count from el_user_prize where user_id = ? or mixnick = ?';
                const userPrize = await connection.executeSql(select_user_prize_sql, [user_id, mixNick]);
                console.log("=============userPrize================", userPrize[0].count);

                if(!userPrize[0].count){
                    //获取奖品清单
                    let select_prize_sql = 'select * from el_prize';
                    const PrizeList = await connection.executeSql(select_prize_sql, []);
                    console.log("================PrizeList===============", PrizeList.length);

                    //抽奖 
                    let Luck = await luckDrawing(PrizeList, type);
                    console.log("=================Luck===================", Luck);
                
                    if (Luck) {
                        let date_current = new Date();
                        let month = date_current.getMonth() + 1;
                        let day = date_current.getDate();

                        month = month > 9 ? month : '0' + month;
                        day = day > 9 ? day : '0' + day;
                        let win_date = '' + month + '-' + day;

                        // 添加抽奖记录
                        let create_user_prize_sql = 'insert into el_user_prize (mixnick, user_id, nick, award_type, prize_name, win_date, name, phone, nick_id, address) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
                        let PrizeRecord = await connection.executeSql(create_user_prize_sql, [mixNick, user_id, nick, Luck.id, Luck.prize_name, win_date, '', '', '', '']);
                        console.log("====================PrizeRecord==================", PrizeRecord);

                        if (PrizeRecord.insertId) {
                            // 减奖品
                            let update_prize_sql = 'update el_prize set total_num = total_num - 1, day_num = day_num - 1 where total_num > 0 and day_num > 0 and id = ?';
                            let updatePrizeInfo = await connection.executeSql(update_prize_sql, [Luck.id]);
                            console.log("====================updatePrizeInfo==================", updatePrizeInfo);

                            if (updatePrizeInfo.affectedRows) {
                                await connection.commit();
                                info.award_type = Luck.id;

                                if(Luck.id == 3){
                                    info.goods_url = 'https://market.m.taobao.com/app/cem-fe/benefit-exchange/benefit-exchange/index.html?source=InterestsDetail&activityId=2349601';
                                }

                                if(Luck.id == 6){
                                    info.goods_url = 'https://market.m.taobao.com/app/cem-fe/benefit-exchange/benefit-exchange/index.html?source=InterestsDetail&activityId=2349597';
                                }

                                console.log('info============================', info);

                                return {
                                    status: "success",
                                    data: info
                                }
                            } else {
                                await connection.rollback();
                                return {
                                    status: "fail",
                                    data: info
                                }
                            }
                        } else {
                            await connection.rollback();
                            return {
                                status: "fail",
                                data: info
                            }
                        }
                    } else {
                        await connection.commit();
                        return {
                            status: "fail",
                            data: info
                        }
                    }
                }else{
                    await connection.commit();
                    return {
                        status: "fail",
                        data: info
                    } 
                }
            } else {
                await connection.commit();
                return {
                    status: "fail",
                    data: info
                }
            }
        } else {
            await connection.commit();
            info.chance = 0;
            return {
                status: "fail",
                data: info
            }
        }
    } catch (err) {
        await connection.rollback();
        return {
            status: "fail",
            data: info
        }
    }
};

// 抽奖ing
async function luckDrawing(prize, type) {
    try {
        //初始化随机数
        let random = await getRandom();
        //初始化奖品概率
        let shopRates = 0;
        //初始阶段
        let startRate = 0;
        //初始化中奖id
        let shopIds = 0;
        //初始值
        let initVal = type == 1 ? 0 : 3;
        //中奖类型长度值
        let typeLength = type == 1 ? 3 : 6;


        console.log("============ //奖池划分，并且抽出奖品===============");
        console.log('random--------------', random);

        //奖池划分，并且抽出奖品
        for (let i = initVal; i < typeLength; i++) {
            //查询概率配置
            if (i == initVal) {
                shopRates += prize[i].probability;
            } else {
                startRate = shopRates;
                shopRates += prize[i].probability;
            }

            console.log('startRate--------------', startRate);
            console.log('shopRates-----------', shopRates);

            //每个产品的概率
            if (random > startRate && random <= shopRates) {
                if(prize[i].total_num > 0 && prize[i].day_num > 0){
                    shopIds = prize[i];
                    break;
                }
            }
        }

        if (shopIds == 0) {
            return false;
        } else {
            return shopIds;
        }
    } catch (err) {
        console.log("===========err================", err)
    }
}

//初始化随机数
function getRandom() {
    let random = (Math.random() * 1000000).toFixed(6);
    return random;
}

//添加埋点信息
exports.addUserStat = async (context) => {
    const {cloud} = context;

    try {
        let paramsData = context.data.stat_data;
        paramsData.userId = context.mixNick;

        let aTralatetTime = new Date().getTime() + 28800000;
        let info = await user.addUserStat(JSON.stringify(paramsData), dateFormat(aTralatetTime, "yyyy-mm-dd hh:MM:ss"), cloud);
        
        return {
            status: "success",
            data: info
        }
    } catch (e) {
        return {
            status: "fail",
            data: err
        }
    }
};

//会员
exports.getMember = async (context) => {
	let {cloud,mixNick} = context;
	try {
		//参数验证
        const result = await cloud.topApi.invoke({
            api: 'taobao.crm.member.identity.get',
            autoSession: true,
            data: {
                'mix_nick': mixNick,
            }
        });
        
        return {
            status: "success",
            data: result
        }
	} catch (e) {
		return {
            status: "fail",
            data: err
        }
	}
};

//获取入会链接
exports.getMemberUrl = async (context) => {
	const { data: { url }, cloud } = context;

	try {
        const result = await cloud.topApi.invoke({
            api: 'taobao.crm.member.joinurl.get',
            autoSession: true,
            data: {
                'callback_url': url,
                'extra_info': '{\"source\":\"isvapp\",\"activityId\":\"12345677\",\"entrance\":\"hudong\"}',
            }
        });

        return {
            status: "success",
            data: result
        }
	} catch (e) {
		return {
            status: "fail",
            data: err
        }
	}
};







//创建中奖用户信息
exports.createPrizeUser = async (context) => {
    const {cloud, data} = context;

    try{
        let info = await userPrize.craetePrizeUser(cloud, data, data.mixNick);

       return {
            status: "success",
            data: info
        } 
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
}

//去重查询
exports.selectGroupBy = async (context) => {
    try{
        let select_sql = 'select * from el_user_prize order by win_date desc limit 100';
        let info = await context.cloud.dataspace.executeSql(select_sql, []);



        return {
            status: "success",
            data: info
        }
    }catch(err){
        return{
            status: "fail",
            data: err
        }
    }
}

//创建奖品信息
exports.createPrize = async (context) => {
    const {cloud, data: {index}} = context;

    try{
        let prize_info = [
            {
                total_num: 25, 
                day_num: 1, 
                fixed_num: 1, 
                prize_name: '肌底微精华限量版正装1份', 
                probability: 1
            },
            {
                total_num: 500, 
                day_num: 20, 
                fixed_num: 20, 
                prize_name: '肌底微精华15ml小样1份', 
                probability: 20
            },
            {
                total_num: 10000, 
                day_num: 400, 
                fixed_num: 400, 
                prize_name: '肌底微精华付邮试用机会', 
                probability: 400
            },
            {
                total_num: 25, 
                day_num: 1, 
                fixed_num: 1, 
                prize_name: '樱花微精华限量版正装1份', 
                probability: 1
            },
            {
                total_num: 1500, 
                day_num: 60, 
                fixed_num: 60, 
                prize_name: '樱花微精华15ml小样1份', 
                probability: 60
            },
            {
                total_num: 10000, 
                day_num: 890, 
                fixed_num: 800, 
                prize_name: '樱花微精华付邮试用机会', 
                probability: 800
            },
        ];
        for(let i = 0; i < prize_info.length; i++){
            let create_info = await prize.createPrize(cloud, prize_info[i]);
            console.log('index create_info--------------', create_info);
        }

        return {
            status: "success",
            data: true
        }
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
};

exports.deleteInfo = async (context) => {
    try{
        // let info = await context.cloud.dataspace.executeSql("update el_user set chance=100 where id=3");
        // let info = await context.cloud.dataspace.executeSql("delete from el_user_prize");
        // let info = await context.cloud.dataspace.executeSql("update el_prize set probability=1000000 where id=3");

        return {
            status: "success",
            data: info
        }
    }catch(err){
        return {
            status: "fail",
            data: err
        }
    }
};
